<?php
namespace dwc_app;

class GoogleFusionAPI extends GoogleAPI
{
    static $service_name = 'fusiontables';
    
    public function create_table($table_name, $fields)
    {
        if(!self::valid_table_or_field_name($table_name))
        {
            echo "invalid table name: $table_name<br>";
            return false;
        }
        $sql = "CREATE TABLE $table_name (";
        $fields_to_add = array();
        foreach($fields as $field_name => $field_type)
        {
            if(!self::valid_table_or_field_name($field_name))
            {
                echo "invalid field name: $field_name<br>";
                return false;
            }
            if(!self::valid_field_type($field_type))
            {
                echo "invalid field_type: $field_type<br>";
                return false;
            }
            $fields_to_add[] = "'$field_name': $field_type";
        }
        $sql .= implode($fields_to_add, ", ") . ")";
        $response = $this->query($sql);
        if(preg_match("/^([0-9]+)$/m", $response, $arr)) return $arr[1];
        return false;
    }
    
    public static function valid_table_or_field_name($name)
    {
        if(preg_match("/^[a-z0-9 ]+$/i", $name, $arr)) return true;
        return false;
    }
    
    public static function valid_field_type($field_type)
    {
        if(in_array($field_type, array('NUMBER', 'STRING', 'LOCATION', 'DATETIME'))) return true;
        return false;
    }
    
    public function query($query)
    {
        if(preg_match("/^(select|show tables|describe)/i", $query))
        {
            $request_url = "http://tables.googlelabs.com/api/query?sql=" . urlencode($query);
            return http_get($request_url, array("Authorization: GoogleLogin auth=" . $this->auth_token));
        }else if(preg_match("/^(create|drop|update|delete|insert)/i", $query))
        {
            $body = "sql=" . urlencode($query);
            $headers = array(
                "Content-length: " . strlen($body),
                "Content-type: application/x-www-form-urlencoded",
                "Authorization: GoogleLogin auth=" . $this->auth_token . " ");
            return http_post("http://tables.googlelabs.com/api/query", $body, $headers);
        }else return false;
    }
}

?>